//
//  NewDiscussionWindowController.m
//  HiQ
//
//  Created by arvintan on 12-7-28.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "MainWindowController.h"
#import "Buddy.h"
#import "BuddyGroup.h"
#import "NewDiscussionWindowController.h"
#import "ImageAndTextCell.h"


@interface NewDiscussionWindowController ()

@end

@implementation NewDiscussionWindowController

@synthesize _headImage;

@synthesize _buttonHeadImage;
@synthesize _outlineBuddyList;
@synthesize _tableSelected;
@synthesize _textselectednum;
@synthesize _textDiscussionName;

@synthesize _buddyListSource;
@synthesize _selectedListSource;


- (void) awakeFromNib
{
    _headImage = [NSImage imageNamed:@"H1"];
    [_buttonHeadImage setImage:_headImage];
    //获取buddy列表
    _buddyListSource = [[MainWindowController sharedMainWindowController] buddySource];
    
    //buddy列表相关设置
    NSTableColumn* column = [_outlineBuddyList tableColumnWithIdentifier:@"BuddyList"];
	ImageAndTextCell* cell = [[ImageAndTextCell alloc] init];
	[column setDataCell: cell];
    [_outlineBuddyList  setDataSource:(id<NSOutlineViewDataSource>)_buddyListSource];  // 设置 buddyList 的 data source
    [_outlineBuddyList  setDelegate:(id<NSOutlineViewDelegate>)self]; // 设置 buddyList 的 delegate
    [_outlineBuddyList  setAction:@selector(onClickBuddyOutlineItem:)];
    [_outlineBuddyList  setDoubleAction:@selector(onDoubleClickBuddyOutlineItem:)];
    [_outlineBuddyList expandItem:[_outlineBuddyList itemAtRow:0]];
    [_outlineBuddyList reloadData];
    
    //新建讨论组table相关设置
    NSTableColumn *selectColumn = [_tableSelected tableColumnWithIdentifier:@"SelectedList"];
    ImageAndTextCell* selectedCell = [[ImageAndTextCell alloc] init];
	[selectColumn setDataCell: selectedCell];
    [_tableSelected setDataSource:_selectedListSource];    //设置tableselected 的 data source
    [_tableSelected setDelegate:(id<NSTableViewDelegate>)self];      //设置tableselected 的 delegate
    [_tableSelected setDoubleAction:@selector(onDoubleClickSelectedTableItem:)];
    [self onMemberChange];
}

- (id)initWithWindow:(NSWindow *)window
{
    self = [super initWithWindow:window];
    if (self) {
        // Initialization code here.
        _selectedListSource = [[NewDiscussionSource alloc] init];
    }
    return self;
}

- (void)windowDidLoad
{
    [super windowDidLoad];
    
    // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}

//改变人数显示
-(void) onMemberChange
{
    [_textselectednum setStringValue:[NSString stringWithFormat:@"%ld/20",[_selectedListSource selectedNum]]];
}

#pragma mark -
#pragma mark click action

- (void)onClickBuddyOutlineItem:(id)sender
{
    // 展开或收起好友列表
    id selectedItem = [_outlineBuddyList itemAtRow:[sender clickedRow]];
    if(selectedItem == nil)
        return;
    if(![_outlineBuddyList isExpandable:selectedItem])
        return;
    if([_outlineBuddyList isItemExpanded:selectedItem])
        [_outlineBuddyList collapseItem:selectedItem];
    else
        [_outlineBuddyList expandItem:selectedItem];
}

- (void)onDoubleClickBuddyOutlineItem:(id)sender
{
    // 双击好友，添加到讨论组
    id selectedItem = [_outlineBuddyList itemAtRow:[sender clickedRow]];
    if(selectedItem == nil)
        return;
    if([_outlineBuddyList isExpandable:selectedItem])
        return;   
    
    [self onAddMember:selectedItem];
}


-(void)onDoubleClickSelectedTableItem:(id)sender
{
    [self onRemoveMember:sender];
}


#pragma mark -
#pragma mark button action
//添加新建讨论组成员
-(IBAction)onAddMember:(id)sender
{
    NSInteger row = [_outlineBuddyList selectedRow] - 1;
    
    NSMutableArray *buddyGroupArray = [[[MainWindowController sharedMainWindowController] buddySource] buddyGroupArray];
    BuddyGroup *group = [buddyGroupArray objectAtIndex:0];
    Buddy *buddy = [group->buddyList objectAtIndex:row];
    
    if ([_selectedListSource selectedNum] >= 20) {
        return;
    }
    [_selectedListSource addMember:buddy];

    [_tableSelected reloadData];
    
    [self onMemberChange];
}

//移出讨论组成员
-(IBAction)onRemoveMember:(id)sender
{
    NSIndexSet *rows = [_tableSelected selectedRowIndexes];
    if ([rows count] == 0)
    {
        NSBeep();
        return;
    }
    
    if([rows firstIndex] == 0)
    {
        NSBeep();
        return;
    }
    
    [_selectedListSource removeMembersAtIndexs:rows];
    [_tableSelected reloadData];
    //[_tableSelected reloadDataForRowIndexes:i columnIndexes:0];
    
    [self onMemberChange];
}


-(IBAction)onCreateNewDiscussion:(id)sender
{
    NSString *discussionName = [_textDiscussionName stringValue];
    if ([discussionName length] == 0) {
        discussionName = @"新的讨论组";
    }
    [_selectedListSource sendNewDiscussionMsg:discussionName HeadIamge:[_headImage name]];
    [self close];
}


-(IBAction)onCancel:(id)sender
{
    [self close];
}

-(IBAction)onSwitchHeadImage:(id)sender
{
    if (_switchHeadImageWindowController == nil)
		_switchHeadImageWindowController = [[SwitchHeadImageWindowController alloc] initWithWindowNibName:@"SwitchHeadImageWindowController"];
	
	// ask our edit sheet for information on the record we want to add
    _headImage = [_switchHeadImageWindowController headImage:self];
    [_buttonHeadImage setImage:_headImage];    
}
#pragma mark - 
#pragma mark tableView delegate

- (void)tableView:(NSTableView *)aTableView willDisplayCell:(id)aCell forTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
{
    if([[aTableColumn identifier] isEqualToString:@"SelectedList"])
    {
        Buddy *buddy = [[_selectedListSource _selectedArray] objectAtIndex:rowIndex];
        NSColor *txtColor;
        if (buddy->status == BUDDY_STATUS_ONLINE)
        {
            [(ImageAndTextCell*)aCell setImage: buddy->onPhoto];
            txtColor = [NSColor blackColor];
        }
        else
        {
            [(ImageAndTextCell*)aCell setImage: buddy->offPhoto];
            //字体为灰
            txtColor = [NSColor colorWithDeviceRed:(161/255.0) green:(161/255.0) blue:(161/255.0) alpha:1.0];
        }
        [(ImageAndTextCell*)aCell setStringValue:buddy->buddyName];
        
        NSFont *txtFont = [NSFont boldSystemFontOfSize:13];
        NSDictionary *txtDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                 txtFont, NSFontAttributeName, txtColor, NSForegroundColorAttributeName, nil];
        NSAttributedString *attrStr = [[NSAttributedString alloc]
                                       initWithString:buddy->buddyName attributes:txtDict];
        [(ImageAndTextCell*)aCell setAttributedStringValue:attrStr];
    }
}
-(BOOL) tableView:(NSTableView *)tableView shouldEditTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
    return NO;
}

#pragma mark - 
#pragma mark outlineView delegate
- (BOOL)outlineView:(NSOutlineView *)outlineView shouldEditTableColumn:(NSTableColumn *)tableColumn item:(id)item
{
    return NO;
}

- (void)outlineView:(NSOutlineView*)olv willDisplayCell:(NSCell*)cell forTableColumn:(NSTableColumn*)tableColumn item:(id)item
{    
    if ([[tableColumn identifier] isEqualToString: @"BuddyList"])
	{
        if([item isKindOfClass:[Buddy class]])
        {
            NSMutableString *buddyName = [[NSMutableString alloc] initWithString:((Buddy*)item)->buddyName];
            NSColor *txtColor;
            if (((Buddy*)item)->status == BUDDY_STATUS_ONLINE)
            {
                [(ImageAndTextCell*)cell setImage: ((Buddy*)item)->onPhoto];
                txtColor = [NSColor blackColor];
            }
            else
            {
                [(ImageAndTextCell*)cell setImage: ((Buddy*)item)->offPhoto];
                //字体为灰
                txtColor = [NSColor colorWithDeviceRed:(161/255.0) green:(161/255.0) blue:(161/255.0) alpha:1.0];
            }
            [(ImageAndTextCell*)cell setStringValue:buddyName];
            
            NSFont *txtFont = [NSFont boldSystemFontOfSize:13];
            NSDictionary *txtDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                     txtFont, NSFontAttributeName, txtColor, NSForegroundColorAttributeName, nil];
            NSAttributedString *attrStr = [[NSAttributedString alloc]
                                           initWithString:buddyName attributes:txtDict];
            [(ImageAndTextCell*)cell setAttributedStringValue:attrStr];
        }
        
        if([item isKindOfClass:[BuddyGroup class]])
        {
            [(ImageAndTextCell*)cell setImage: nil];
        }
        
    }
}

@end
